package com.bootdo.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bootdo.contract.dao.YutableDao;
import com.bootdo.contract.domain.YumemberDO;
import com.bootdo.contract.domain.YutableDO;
import com.bootdo.contract.service.YumemberService;
import com.bootdo.contract.service.YutableService;
import com.bootdo.system.service.RoleService;
import org.apache.catalina.manager.util.SessionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.RandomValidateCodeUtil;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.MenuDO;
import com.bootdo.system.service.MenuService;

@Controller
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MenuService menuService;
    @Autowired
    RoleService roleService;
    @Autowired
    FileService fileService;
    @Autowired
    BootdoConfig bootdoConfig;
    @Autowired
    YutableService yutableService;
    @Autowired
    YumemberService yumemberService;

    @GetMapping({"/", ""})
    String welcome(Model model) {
//        return "redirect:/blog";
        return "login";
    }

    @Log("请求访问主页")
    @GetMapping({"/index"})
    String index(Model model, String id, HttpServletRequest request) {
        if (null == id || id.equals("")) {
            List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
            model.addAttribute("menus", menus);
            model.addAttribute("name", getUser().getName());
            FileDO fileDO = fileService.get(getUser().getPicId());
            if (fileDO != null && fileDO.getUrl() != null) {
                if (fileService.isExist(fileDO.getUrl())) {
                    model.addAttribute("picUrl", fileDO.getUrl());
                } else {
                    model.addAttribute("picUrl", "/img/photo_s.jpg");
                }
            } else {
                model.addAttribute("picUrl", "/img/photo_s.jpg");
            }
            model.addAttribute("username", getUser().getUsername());
            return "index_v1";
        } else {
            HttpSession session = request.getSession();
            session.setAttribute("yuid", id);
            List<Tree<MenuDO>> menus = new ArrayList<>();
            Long userId = getUserId();
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("manager", userId);
            List<YutableDO> list = yutableService.list(map);
            if (list.size() >= 1) {
                menus = menuService.getYuSysMenuTree();
            }
            Map<String, Object> map2 = new HashMap<>();
            map2.put("yuid", id);
            map2.put("renyuanid", userId);
            List<YumemberDO> list1 = yumemberService.list(map2);
            if (list1.size() >= 1) {
                YumemberDO yumemberDO = list1.get(0);
                Integer zhiwu = yumemberDO.getZhiwu();
                if (zhiwu == 1) {
                    List<Tree<MenuDO>> teacherSysMenuTree = menuService.getTeacherSysMenuTree();
                    for (int i = 0; i < teacherSysMenuTree.size(); i++) {
                        menus.add(teacherSysMenuTree.get(i));
                    }
                }
            }
            model.addAttribute("menus", menus);
            model.addAttribute("name", getUser().getName());
            FileDO fileDO = fileService.get(getUser().getPicId());
            if (fileDO != null && fileDO.getUrl() != null) {
                if (fileService.isExist(fileDO.getUrl())) {
                    model.addAttribute("picUrl", fileDO.getUrl());
                } else {
                    model.addAttribute("picUrl", "/img/photo_s.jpg");
                }
            } else {
                model.addAttribute("picUrl", "/img/photo_s.jpg");
            }
            model.addAttribute("username", getUser().getUsername());
            model.addAttribute("yuid", id);
            return "index_v1";
        }

    }

    @Log("非超管链接")
    @GetMapping("/listyu")
    String listYu(Model model) {
        Map<String, Object> map = new HashMap<>();
        Long userId = getUserId();
        map.put("manager", userId);
        map.put("sort", "createtime");
        List<YutableDO> list = yutableService.list(map);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("renyuanid", userId);
        List<YumemberDO> list1 = yumemberService.list(map2);
        for (int i = 0; i < list1.size(); i++) {
            YumemberDO yumemberDO = list1.get(i);
            Integer yuid = yumemberDO.getYuid();
            YutableDO yutableDO = yutableService.get(yuid);
            boolean flag = true;
            for (int j = 0; j < list.size(); j++) {
                YutableDO yutableDO1 = list.get(j);
                if (yutableDO1.getId() == yutableDO.getId()) {
                    flag = false;
                    break;
                }
            }
            if (flag == true) {
                list.add(yutableDO);
            }

        }
        model.addAttribute("list", list);
        return "listyu";
    }

    @GetMapping("/login")
    String login(Model model) {
        model.addAttribute("username", bootdoConfig.getUsername());
        model.addAttribute("password", bootdoConfig.getPassword());
        return "login";
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    R ajaxLogin(String username, String password, String verify, HttpServletRequest request) {
/*        try {
            //从session中获取随机数
            String random = (String) request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
            if (StringUtils.isBlank(verify)) {
                return R.error("请输入验证码");
            }
            if (random.equals(verify)) {
            } else {
                return R.error("请输入正确的验证码");
            }
        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return R.error("验证码校验失败");
        }*/
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            Map<String, Object> map = new HashMap<>();
            subject.login(token);
            map.put("code", 0);
            Long userId = getUserId();
            int frindroleid = roleService.frindroleid(userId);
            map.put("id", frindroleid);
            return R.ok(map);
        } catch (AuthenticationException e) {
            return R.error("未找到用户");
        }
    }

    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }

    @GetMapping("/main")
    String main() {
        return "main";
    }

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>> ", e);
        }
    }

}
